package com.pick.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pick.admin.entity.SysOperationLog;
import com.pick.admin.mapper.SysOperationLogMapper;
import com.pick.admin.service.SysOperationLogService;
import com.pick.base.common.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 系统操作日志服务实现类
 */
@Service
@Slf4j
public class SysOperationLogServiceImpl extends ServiceImpl<SysOperationLogMapper, SysOperationLog> implements SysOperationLogService {
    
    @Override
    public IPage<SysOperationLog> pageOperationLogs(PageQuery pageQuery) {
        Page<SysOperationLog> page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
        LambdaQueryWrapper<SysOperationLog> wrapper = new LambdaQueryWrapper<>();
        
        // 关键字搜索
        if (StrUtil.isNotBlank(pageQuery.getKeyword())) {
            wrapper.like(SysOperationLog::getUsername, pageQuery.getKeyword())
                    .or().like(SysOperationLog::getModule, pageQuery.getKeyword())
                    .or().like(SysOperationLog::getOperationType, pageQuery.getKeyword())
                    .or().like(SysOperationLog::getDescription, pageQuery.getKeyword());
        }
        
        // 排序
        if (StrUtil.isNotBlank(pageQuery.getOrderBy())) {
            if ("ASC".equalsIgnoreCase(pageQuery.getOrder())) {
                wrapper.orderByAsc(SysOperationLog::getOperationTime);
            } else {
                wrapper.orderByDesc(SysOperationLog::getOperationTime);
            }
        } else {
            wrapper.orderByDesc(SysOperationLog::getOperationTime);
        }
        
        return this.page(page, wrapper);
    }
    
    @Override
    public boolean saveOperationLog(SysOperationLog operationLog) {
        try {
            operationLog.setOperationTime(LocalDateTime.now());
            return this.save(operationLog);
        } catch (Exception e) {
            log.error("保存操作日志失败", e);
            return false;
        }
    }
    
    @Override
    public int cleanExpiredLogs(int days) {
        try {
            LocalDateTime expiredTime = LocalDateTime.now().minusDays(days);
            LambdaQueryWrapper<SysOperationLog> wrapper = new LambdaQueryWrapper<>();
            wrapper.lt(SysOperationLog::getOperationTime, expiredTime);
            
            int count = Math.toIntExact(this.count(wrapper));
            this.remove(wrapper);
            
            log.info("清理过期操作日志 {} 条，保留天数: {}", count, days);
            return count;
        } catch (Exception e) {
            log.error("清理过期操作日志失败", e);
            return 0;
        }
    }
}